package com.amit.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet 
{
	
	public DownloadServlet()
	{
		System.out.println("defulat");
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
String fileName=request.getParameter("fileName");
String mimeType=getServletContext().getMimeType(fileName);
if(mimeType==null)
{
	mimeType="application/octet-stream";
}

String dir=request.getRealPath("/WEB-INF/files");
File file=new File(dir, fileName);
response.setContentType(mimeType);
response.setContentLength((int)file.length());
if(file.getName().endsWith(".pdf")||file.getName().endsWith(".doc"))
{
	
	response.setHeader("Content-Disposition", "inline;filename="+fileName);
}
else
{
	response.setHeader("Content-Disposition", "attachment;filename="+fileName);
}
	
OutputStream out=response.getOutputStream();
FileInputStream fis=new FileInputStream(file);
while(true)
{
	int ab=fis.read();
	if(ab==-1)
	break;
	out.write(ab);
}
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request, response);
	}
	
	

}
